import {Layout, Menu} from 'antd'
import type { MenuProps } from 'antd'
import { useEffect, useState} from 'react'
import type { NonIndexRouteObject } from 'react-router-dom'
import { useLocation, useNavigate } from 'react-router-dom'
import { useSelector } from 'react-redux'
import {routes} from '../routers'
 

const {Sider} = Layout

const Nav = () =>{
    const [menuItem, setMenuItem] = useState<MenuProps['items']>([])
    const [selectedKeys, setSelectedKeys] = useState<string[]>([])
    const navigate = useNavigate()
    const location = useLocation()
    const isDark = useSelector((state: unknown) => (state as { theme: { isDark: boolean } }).theme.isDark)

    useEffect(() => {
        const items: MenuProps['items'] = (routes[0]?.children as NonIndexRouteObject[] | undefined)
          ?.flatMap((item) => {
            const key = (item.path ?? (typeof item.label === 'string' ? item.label : ''))?.trim()
            return key ? [{ key, label: item.label, icon: item.icon }] : []
          }) ?? []
          console.log(items)
        setMenuItem(items)

        const pathname = location.pathname
        const currentKey = (pathname.startsWith('/') ? pathname.slice(1) : pathname) || ''
        const keys = (items as Exclude<MenuProps['items'], undefined>).map(i => String((i as { key: React.Key }).key))
        const initial = currentKey && keys.includes(currentKey) ? currentKey : (keys[0] ?? '')
        setSelectedKeys(initial ? [initial] : [])
    }, [location.pathname])
    return (<> 
     <Sider width={200}>
         <Menu
           mode="inline"
           selectedKeys={selectedKeys}
           style={{ 
             height: '100%', 
             borderInlineEnd: 0
           }}
           theme={isDark ? 'dark' : 'light'}
           items={menuItem}
           onClick={({ key }) => {
             const k = String(key)
             setSelectedKeys([k])
             navigate(k.startsWith('/') ? k : `/${k}`)
           }}
         />
        </Sider> 
    </>)
}

export default Nav
